#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/4/10
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R29_EC_UpaidBusinessOfConcCheck
# @Software  :PyCharm


'''eof
name:申请企业未结清业务五级分类校验（关注类）
code:R29_EC_UpaidBusinessOfConcCheck_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime


reload(sys)
sys.setdefaultencoding('utf-8')

"""
"FACTOR1 = 统计未结清借贷交易汇总信息段(EB02A)-其他借贷交易分类汇总信息(EB02AH)·业务类型(EB02AD01)∈(1(中长期借款),2(短期借款),3(循环透支))(由于该指标剔除了“票据贴现”的业务类型，因此业务类型里不能加“合计”)且资产质量分类(EB02AD02)为“2(关注类)”的账户数(EB02AS04)或余额(EB02AJ06)＞0的记录数
FACTOR2 = 统计未结清担保交易汇总信息段(EB03A)-未结清担保交易汇总信息(EB03AH)·业务类型(EB03AD01)∈(银行承兑汇票or信用证or银行保函or其他)且资产质量分类(EB03AD02)为“2(关注类)”的账户数(EB03AS02)或余额(EB03AJ01)＞0的记录数
FACTOR3 = 统计借贷账户信息单元-基本信息段(ED01A)-账户活动状态(ED01AD01)为“1(未结清)”且借贷账户类型(ED01AD02)不为“D2(贴现账户)”且还款表现信息段(ED01B)-还款表现信息(ED01BH)·五级分类(ED01BD01)为“2(关注类)”的记录数
FACTOR4 = 统计担保信息单元-基本信息段(ED04A)·担保账户类型(ED04AD01)∈(G1(融资担保账户),G2(非融资担保账户),G3(支付担保账户))且在保责任信息段(ED04B)·账户活动状态(ED04BD01)为“1(未结清)”且五级分类(ED04BD02)为“2(关注类)”的记录数
FACTOR5 = 统计信贷交易提示息段(EB01A)·关注类担保交易余额(EB01AJ06)＞0的记录数
FACTOR = MAX(FACTOR1,FACTOR2,FACTOR3,FACTOR4,FACTOR5)"

:return:
"""

def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = EC_DSJ_2D["data"].get(table_Name)
        if data is None:
            return None
        elif data == "" or (isinstance(data, list) and len(data) == 0):
            return [{}]
        else:
            return data
    except:
        return None

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']



# Factor1
def table_1(EBB):
    if EBB is None:
        return None
    elif EBB == [{}]:
        return 0
    else:
        EB02 = EBB[0].get("EB02")                               # 借贷交易汇总信息单元
        if EB02 == "":
            return 0
        elif EB02 in null_type_list:
            return None
        else:
            EB02A = EB02[0].get("EB02A")
            if EB02A is None:
                return None
            else:
                EB02AH = EB02A[0].get("EB02AH")                 # 其他借贷交易分类汇总信息
                if EB02AH is None:
                    return 0
                else:
                    factor_tmp=[]
                    for i in range(len(EB02AH)):
                        EB02AD01 = EB02AH[i].get("EB02AD01")    # 业务类型
                        EB02AD02 = EB02AH[i].get("EB02AD02")    # 资产质量分类
                        EB02AS04 = EB02AH[i].get("EB02AS04")    # 账户数
                        EB02AJ06 = EB02AH[i].get("EB02AJ06")    # 余额

                        if EB02AD01 is None or EB02AD02 is None or \
                                (EB02AS04 is None and EB02AJ06 is None):
                            factor_tmp.append(None)
                        else:
                            if convertDataType(EB02AD01, 'str') in ['1', '2', '3'] and \
                                    convertDataType(EB02AD02, 'str') == '2':
                                if isFloat(EB02AS04) or isFloat(EB02AJ06):
                                    EB02AS04 = convertDataType(EB02AS04, 'float')
                                    EB02AS04 = 0 if EB02AS04 is None else EB02AS04
                                    EB02AJ06 = convertDataType(EB02AJ06, 'float')
                                    EB02AJ06 = 0 if EB02AJ06 is None else EB02AJ06
                                    if EB02AS04 > 0 or EB02AJ06 > 0:
                                        factor_tmp.append(1)
                                    else:
                                        factor_tmp.append(0)
                            else:
                                factor_tmp.append(0)
                    FactorNotNone = filter(lambda x: x is not None, factor_tmp)
                    if len(FactorNotNone) == 0:
                        return None
                    else:
                        Factor = sum(FactorNotNone)
                        return Factor


# Factor2
def table_2(EBC):
    if EBC is None:
        return None
    elif EBC == [{}]:
        return 0
    else:
        EB03 = EBC[0].get("EB03")
        if EB03 is None:
            return 0
        elif EB03 == "":
            return None
        else:
            EB03A = EB03[0].get("EB03A")
            if EB03A is None:
                return None
            elif EB03A == "":
                return None
            else:
                EB03AH = EB03A[0].get("EB03AH")     # 未结清担保交易汇总信息
                if EB03AH is None:
                    return 0
                elif EB03AH == "":
                    return None
                else:
                    factor_tmp = []
                    for i in range(len(EB03AH)):
                        EB03AD01 = EB03AH[i].get("EB03AD01")  # 业务类型
                        EB03AD02 = EB03AH[i].get("EB03AD02")  # 资产质量分类
                        EB03AS02 = EB03AH[i].get("EB03AS02")  # 账户数
                        EB03AJ01 = EB03AH[i].get("EB03AJ01")  # 余额

                        if EB03AD01 is None or EB03AD02 is None or (EB03AS02 is None and EB03AJ01 is None):
                            factor_tmp.append(None)
                        else:
                            if convertDataType(EB03AD01, 'str') in ['1', '2', '3', '9'] and \
                                    convertDataType(EB03AD02, 'str') == '2':
                                if isFloat(EB03AS02) or isFloat(EB03AJ01):
                                    EB03AS02 = convertDataType(EB03AS02, 'float')
                                    EB03AS02 = 0 if EB03AS02 is None else EB03AS02
                                    EB03AJ01 = convertDataType(EB03AJ01, 'float')
                                    EB03AJ01 = 0 if EB03AJ01 is None else EB03AJ01
                                    if EB03AJ01 > 0 or EB03AS02 > 0:
                                        factor_tmp.append(1)
                                    else:
                                        factor_tmp.append(0)
                                else:
                                    factor_tmp.append(0)
                            else:
                                factor_tmp.append(0)
                    FactorNotNone = filter(lambda x: x is not None, factor_tmp)
                    if len(FactorNotNone) == 0:
                        return None
                    else:
                        Factor = sum(FactorNotNone)
                        return Factor

# Factor3
def table_3(EDA):
    if EDA is None:
        return None
    elif EDA == [{}]:
        return 0
    else:
        ED01 = EDA[0].get("ED01")   # 借贷账户信息单元
        if ED01 is None:
            return 0
        elif ED01 == "":
            return None
        else:
            factor_tmp=[]
            for i in range(len(ED01)):
                ED01A = ED01[i].get("ED01A")    # 基本信息段
                ED01B = ED01[i].get("ED01B")    # 还款表现
                if ED01A is None or ED01B is None:
                    factor_tmp.append(None)
                elif ED01B == "":
                    factor_tmp.append(0)
                else:
                    ED01AD01 = ED01A[0].get("ED01AD01")  # 账户活动状态
                    ED01AD02 = ED01A[0].get("ED01AD02")  # 借贷账户类型
                    ED01BH = ED01B[0].get("ED01BH")      # 还款表现信息
                    if ED01BH in null_type_list or ED01AD01 in null_type_list or ED01AD02 in null_type_list:
                        factor_tmp.append(None)
                        continue
                    else:
                        # 取最新的信息报告日期的五级分类为准
                        fiveClass = None
                        latestDate = None
                        for j in range(len(ED01BH)):
                            ED01BD01 = ED01BH[j].get("ED01BD01")  # 五级分类
                            ED01BR01 = ED01BH[j].get("ED01BR01") # 信息报告日期
                            if ED01BD01 in null_type_list or ED01BR01 in null_type_list:
                                continue
                            else:
                                if j == 0:
                                    fiveClass = ED01BD01
                                    latestDate = ED01BR01
                                if ED01BR01 > latestDate:
                                    latestDate = ED01BR01
                                    fiveClass = ED01BD01
                        if ED01AD01 in null_type_list or ED01AD02 in null_type_list or fiveClass is None:
                            factor_tmp.append(None)
                        else:
                            if convertDataType(ED01AD01, 'str') == '1' and \
                                    convertDataType(ED01AD02, 'str') != 'D2' and \
                                    convertDataType(fiveClass, 'str') == '2':
                                factor_tmp.append(1)
                            else:
                                factor_tmp.append(0)
            FactorNotNone = filter(lambda x: x is not None, factor_tmp)
            if len(FactorNotNone) == 0:
                return None
            else:
                Factor = sum(FactorNotNone)
                return Factor

# Factor4
def table_4(EDB):
    if EDB is None:
        return None
    elif EDB == [{}]:
        return 0
    else:
        ED04 = EDB[0].get("ED04")     # 担保账户信息明细单元
        if ED04 is None:
            return 0
        else:
            factor_tmp = []
            for i in ED04:
                ED04A = i.get("ED04A")
                ED04B = i.get("ED04B")
                if ED04A is None or ED04B is None:
                    factor_tmp.append(None)
                else:
                    ED04AD01 = ED04A[0].get("ED04AD01")   # 担保账户类型
                    ED04BD01 = ED04B[0].get("ED04BD01")   # 账户活动状态
                    ED04BD02 = ED04B[0].get("ED04BD02")   # 五级分类
                    if ED04AD01 is None or ED04BD01 is None or ED04BD02 is None:
                        factor_tmp.append(None)
                    else:
                        if convertDataType(ED04AD01, 'str') in ['G1', 'G2', 'G3'] and \
                                convertDataType(ED04BD01, 'str') == '1' and \
                                convertDataType(ED04BD02, 'str') == '2':
                            factor_tmp.append(1)
                        else:
                            factor_tmp.append(0)
        FactorNotNone = filter(lambda x: x is not None, factor_tmp)
        if len(FactorNotNone) == 0:
            return None
        else:
            Factor = sum(FactorNotNone)
            return Factor

# Factor5
def table_5(EBA):
    if EBA is None:
        return None
    elif EBA == [{}]:
        return 0
    else:
        EB01 = EBA[0].get("EB01")
        if EB01 is None:
            return None
        elif EB01 == "":
            return 0
        else:
            factor_tmp=[]
            EB01A = EB01[0].get("EB01A")     # 信贷交易提示信息
            if EB01A is None:
                factor_tmp.append(0)
            else:
                # EB01AJ03 = EB01A[0].get("EB01AJ03")   # 关注类借贷交易余额
                EB01AJ06 = EB01A[0].get("EB01AJ06")   # 关注类担保交易余额
                if EB01AJ06 is None:
                    factor_tmp.append(None)
                else:
                    if isFloat(EB01AJ06) and convertDataType(EB01AJ06, 'float') > 0:
                        factor_tmp.append(1)
                    else:
                        factor_tmp.append(0)
            FactorNotNone = filter(lambda x: x is not None, factor_tmp)
            if len(FactorNotNone) == 0:
                return None
            else:
                Factor = sum(FactorNotNone)
                return Factor


def R29_EC_UpaidBusinessOfConcCheck():
    try:
        EBB = formatData("EBB")  # 借贷交易汇总信息
        EBC = formatData("EBC")  # 担保交易汇总信息
        EDA = formatData("EDA")  # 借贷账户信息
        EDB = formatData("EDB")  # 担保账户信息
        EBA = formatData("EBA")  # 信用提示信息

        Factor1=table_1(EBB)
        Factor2=table_2(EBC)
        Factor3=table_3(EDA)
        Factor4=table_4(EDB)
        Factor5=table_5(EBA)
        Factor=[Factor1,Factor2,Factor3,Factor4,Factor5]
        FactorNotNone = filter(lambda x: x is not None, Factor)
        if len(FactorNotNone)==0:
            return u"缺失值"
        else:
            Factor = max(FactorNotNone)
            return Factor
    except:
        u"缺失值"

result = R29_EC_UpaidBusinessOfConcCheck()


